/**
 * @desc: 价格管理
 * @author: binlety
 */
import React, { useState, useEffect, useRef } from "react";
import { Button, Modal, message } from "antd";
import IconFont from "@/components/IconFont";
import CommonLoading from "@/components/CommonLoading";
import HeaderTab from "@/components/CommonTab";
import PriceSearch from "./component/PriceSearch";
import PriceList from "./component/PriceTableList";
import ApplyMemberPriceModal from "./component/ApplyModal";
import ExportModal from "./component/ExportModal";
import FooterToolbar from "@/components/FooterToolbar";
import CommonPagination from "@/components/CommonPagination";
import {
	getPriceList,
	getLogList,
	exportVipPrice,
	getGoodsCustomLogList,
	custompricecheckOp,
	exprotForTab6Op,
	exprotForTab7Op
} from "./service";
import { excelExport } from "@/utils/utils.jsx";
import moment from "moment";
import PriceConfigModal from "./component/PriceConfigModal";
import styles from "./index.module.less";
import { useNavigate } from "react-router-dom";

const tabArr = [
	//顶部tab信息
	{ key: "2", tab: "使用中" },
	{ key: "1", tab: "待审核" },
	{ key: "3", tab: "审核失败" },
	{ key: "4", tab: "已作废" },
	{ key: "5", tab: "改价审核" },
	{ key: "6", tab: "改价审核日志" },
	{ key: "7", tab: "自定义改价日志" },
	{ key: "8", tab: "供应商匹配改价" }
];

const statusMap = {
	待审核: 5,
	审核通过: 2,
	审核拒绝: 3
};

const initPagination = {
	current: 1,
	total: 0,
	pageSize: 10,
	showSizeChange: true,
	showQuickJumper: true
}; //分页

const column = [
	{
		title: `${APP_TITLE}编码`,
		dataIndex: "goodsId",
		key: "goodsId"
	},
	{
		title: "会员价",
		dataIndex: "vipPrice",
		key: "vipPrice"
	},
	{
		title: "失败原因",
		dataIndex: "remark",
		key: "remark"
	}
];

let searchKey = 0;

const PriceManage = () => {
	const [loading, setLoading] = useState(false);
	const [type, setType] = useState("2");
	const [query, setQuery] = useState({});
	const [data, setData] = useState([]);
	const [pagination, setPage] = useState(initPagination); //分页
	const [visible, setVisible] = useState(false); //1.申请会员价弹窗  2 会员价导入弹窗  3 改价弹窗
	const navigate = useNavigate();
	const currentStatus = useRef(5);

	const status = currentStatus.current;

	const requestParams = useRef(null);

	useEffect(() => {
		getTableListFunc(); //表格分页
	}, [pagination]);

	//主列表数据
	const getTableListFunc = async () => {
		searchKey++;
		if (data.length) {
			setData([]);
		}
		const values = {
			...query,
			current: pagination.current,
			size: pagination.pageSize
		};
		if (values.apply_time) {
			if (type == 8) {
				values.applyStartTime = moment(values.apply_time[0]._d).format("YYYY-MM-DD HH:mm:ss");
				values.applyEndTime = moment(values.apply_time[1]._d).format("YYYY-MM-DD HH:mm:ss");
			} else {
				values.addStartTime = moment(values.apply_time[0]._d).format("YYYY-MM-DD HH:mm:ss");
				values.addEndTime = moment(values.apply_time[1]._d).format("YYYY-MM-DD HH:mm:ss");
			}
		}
		values.apply_time = undefined;
		if (values.audit_time) {
			if (type == 6 || type == 8) {
				if (type == 6) {
					values.auditBeginTime = moment(values.audit_time[0]._d).format("YYYY-MM-DD HH:mm:ss");
					values.auditEndTime = moment(values.audit_time[1]._d).format("YYYY-MM-DD HH:mm:ss");
				} else if (status != 5) {
					values.auditStartTime = moment(values.audit_time[0]._d).format("YYYY-MM-DD HH:mm:ss");
					values.auditEndTime = moment(values.audit_time[1]._d).format("YYYY-MM-DD HH:mm:ss");
				}
			} else {
				values.verifyStartTime = moment(values.audit_time[0]._d).format("YYYY-MM-DD HH:mm:ss");
				values.verifyEndTime = moment(values.audit_time[1]._d).format("YYYY-MM-DD HH:mm:ss");
			}
		}
		if (values.generation_time) {
			values.startTime = moment(values.generation_time[0]._d).format("YYYY-MM-DD HH:mm:ss");
			values.endTime = moment(values.generation_time[1]._d).format("YYYY-MM-DD HH:mm:ss");
		}
		requestParams.current = {
			//附带审核时间 生成时间字段
			...values,
			current: 1,
			size: 5000
		};
		values.generation_time = undefined;
		values.audit_time = undefined;
		setLoading(true);
		if (type != 6 && type != 7 && type != 8) {
			values.verifyStatus = type;
			// values.auditUserName = undefined
			// values.taskUserName = undefined
			// values.status = undefined
			const { data, success } = await getPriceList(values);
			setLoading(false);
			if (success) {
				const { records = [], total } = data;
				records.map((item, index, _self) => {
					let stage = 0;
					item.goodsPriceVos.map(items => {
						stage += items.goodsColorPriceVos.length;
					});
					_self[index].stage = stage;
				});
				const pageTableData = [];
				records.map(item => {
					item.goodsPriceVos.map((items, indexs) => {
						let rowSpan_sku = items.goodsColorPriceVos.length;
						items.goodsColorPriceVos.map((child, childs) => {
							pageTableData.push({
								...item,
								...child,
								size: items.size,
								goodsPriceVos: null,
								stage: null,
								rowSpan_spu: indexs || childs ? 0 : item.stage,
								rowSpan_sku: childs ? 0 : rowSpan_sku
							});
						});
					});
				});
				// console.log(pageTableData)
				pagination.total = total;
				setPage(pagination);
				setData(pageTableData);
			} else {
				pagination.total = 0;
				setPage(pagination);
				setData([]);
			}
		} else {
			let res;
			if (type == 6) {
				res = await getLogList(values);
			} else if (type == 7) {
				res = await getGoodsCustomLogList(values);
			} else if (type == 8) {
				values.state = status;
				if (status == 5) {
					values.auditor = undefined;
				}
				res = await custompricecheckOp(values);
			}
			const { data, success } = res;
			if (success) {
				const { records = [], total } = data;
				pagination.total = total;
				setPage(pagination);
				setData(records);
			} else {
				pagination.total = 0;
				setPage(pagination);
				setData([]);
			}
			setLoading(false);
		}
	};

	// tab区
	const HeaderTabProps = {
		type,
		data: tabArr,
		onChange(val) {
			setData([]);
			setType(val);
			setQuery({});
			setPage({
				...pagination,
				current: 1
			});
		}
	};

	// 搜索区
	const PriceSearchProps = {
		type,
		query,
		status,
		handleOk(values) {
			setQuery(values);
			setPage({
				...pagination,
				current: 1
			});
		},
		handleCancel() {
			setQuery({});
			setPage({
				...pagination,
				current: 1
			});
		}
	};

	// 列表区
	const PriceListProps = {
		type,
		data,
		status,
		searchKey,
		openApplyModal() {
			setVisible(1);
		},
		updateList() {
			setPage({
				...pagination,
				current: 1
			});
		}
	};

	//分页
	const pageProps = {
		pagination,
		handleChange: function (current, pageSize) {
			setPage({
				...pagination,
				current,
				pageSize
			});
		}
	};

	// 申请弹窗
	const ApplyModalProps = {
		visible: visible == 1,
		handleOk() {
			if (type == 1) {
				//如果是待审核页面即刷新
				setPage({
					...pagination
				});
			}
		},
		handleCancel() {
			setVisible(false);
		}
	};

	//批量申请弹窗
	const ExportModalProps = {
		visible: visible == 2,
		handleCancel() {
			setVisible(false);
		},
		handleOk(file) {
			handlExportVipPrice(file);
		}
	};

	//改价配置弹窗
	const PriceConfigModalProps = {
		visible: visible == 3,
		isCustom: type == 8,
		handleCancel() {
			setVisible(false);
		}
	};

	//会员价导入
	const handlExportVipPrice = async file => {
		if (Object.keys(file).length > 0) {
			setLoading(true);
			const { success, data } = await exportVipPrice({ file: file });
			if (success) {
				Modal.confirm({
					className: "views-modal-confirm",
					centered: true,
					title: "提示",
					content: (
						<div>
							<span className="common-color10">成功</span>导入{data.successNum}条，<span className="common-color9">失败</span>
							{data.failNum}条
						</div>
					),
					okText: "导出失败内容",
					okButtonProps: { disabled: data.failNum == "0" ? true : false }, //失败条数为0时不能导出失败内容
					onOk() {
						excelExport({
							fileName: "失败详情",
							suffix: "csv",
							titles: column.map(item => item.title),
							dataSource: (data.data || []).map(({ goodsId, vipPrice, remark }) => [goodsId, vipPrice, remark])
						});
					}
				});
			}
			setVisible(false);
			setLoading(false);
		} else {
			message.warning("文件为空，请上传文件！");
		}
	};

	const handleChangeStatus = e => {
		const value = e.target.id;
		if (value) {
			currentStatus.current = value;
			setPage({
				...pagination,
				current: 1
			});
		}
	};

	//导出api
	const exportExcel = async () => {
		if (!pagination.total) {
			return message.info("暂无可导出的数据！");
		}
		if (pagination.total > 5000) {
			return message.info("表格导出最多5000条, 请重新筛选！");
		}
		const params = requestParams.current;
		if ((type == 6 && !params.audit_time) || (type == 7 && !params.generation_time)) {
			return message.info("请先选择时间范围");
		}
		delete params.audit_time;
		delete params.generation_time;
		setLoading(true);
		let res;
		if (type == 6) {
			res = await exprotForTab6Op(params);
		} else {
			res = await exprotForTab7Op(params);
		}
		const { success } = res || {};
		setLoading(false);
		if (success) {
			Modal.confirm({
				className: "views-modal-confirm",
				centered: true,
				icon: <IconFont type="iconchenggong" />,
				title: <span className="common-color10">成功提示</span>,
				content: (
					<div>
						您的文件正在导出中 <br />
						可以去“任务中心”查看导出进度和结果！
					</div>
				),
				okText: "去查看",
				cancelText: "关闭",
				onOk() {
					navigate(`/basic/taskCenter`);
				}
			});
		}
	};

	return (
		<>
			<div className="zjf-container">
				<HeaderTab {...HeaderTabProps} />
				<PriceSearch {...PriceSearchProps} />
				<div className="common-table-header-btn">
					{["1", "2", "3", "4"].includes(type) && (
						<>
							<Button style={{ marginRight: "6px" }} onClick={() => setVisible(1)}>
								申请会员价
							</Button>
							<Button style={{ marginRight: "6px" }} onClick={() => setVisible(2)}>
								批量导入
							</Button>
						</>
					)}
					{type != 6 && type != 7 && <Button onClick={() => setVisible(3)}>改价设置</Button>}
					{(type == 6 || type == 7) && <Button onClick={exportExcel}>导出</Button>}
				</div>
				{type == 8 && (
					<div className={styles.customTab} onClick={handleChangeStatus}>
						{Object.keys(statusMap).map(item => {
							const value = statusMap[item];
							return (
								<div className={value == status ? styles.tabActive : styles.tabItem} key={value} id={value}>
									{item}
								</div>
							);
						})}
					</div>
				)}
				<PriceList {...PriceListProps} key={searchKey} />
				<ApplyMemberPriceModal {...ApplyModalProps} />
				<PriceConfigModal {...PriceConfigModalProps} />
				<ExportModal {...ExportModalProps} />
			</div>
			<FooterToolbar>
				<CommonPagination {...pageProps} />
			</FooterToolbar>
			<CommonLoading loading={loading} />
		</>
	);
};

export default React.memo(PriceManage, () => {
	return true;
});
